<script setup lang="ts">
import { mdiPlus } from '@mdi/js'
import { useDropHandle } from '@/composables/dragAndDrop/useDropHandle'
import DropIndicator from '@/windows/layoutBrowser/components/common/DropIndicator.vue'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import { useSidebarStore } from '@/windows/layoutBrowser/stores/sidebar'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import {
  handleResolvedDrop,
  resolveBrowserTabOrGroup
} from '@/composables/dragAndDrop/dragDropUtil'

const layoutStore = useLayoutStore()
const props = defineProps<{
  direction: 'left' | 'right' | 'top'
  iconSize?: number | string
}>()
const sidebarStore = useSidebarStore()
const tabStore = useTabStore()
const tabElementRef = ref<HTMLDivElement>()
const { dropState } = useDropHandle({
  el: tabElementRef,
  acceptedTypes: ['sidebar-tab', 'browser-tab', 'browser-tab-group'],
  onDrop: (source, edge, isExternal) => {
    const sidebarTab = source['sidebar-tab']
    const browserTab = source['browser-tab']
    if (props.direction === 'top') {
      const targetTab = tabStore.tabs.at(-1)
      const resolved = resolveBrowserTabOrGroup(source)
      handleResolvedDrop(
        resolved,
        targetTab?.id,
        true,
        isExternal,
        tabStore.moveTabRelativeToAnother
      )
    } else {
      const isRight = props.direction === 'right'
      const sidebars = isRight ? sidebarStore.rightTabs : sidebarStore.leftTabs

      if (sidebarTab) {
        if (sidebarTab.direction === props.direction) {
          // 计算目标位置（同侧重排）
          const sourceIndex = sidebarTab.index

          const finalTargetIndex = sidebars.length - 1

          // 执行边栏标签页移动操作
          if (sourceIndex !== finalTargetIndex) {
            sidebarStore.moveSidebarTab(sourceIndex, finalTargetIndex, isRight)
          }
        } else {
          // 跨侧边栏移动
          const finalTargetIndex = sidebars.length
          sidebarStore.moveSidebarTabAcrossSides(sidebarTab.id, isRight ?? false, finalTargetIndex)
        }
      } else if (browserTab) {
        if (!browserTab.data?.url) {
          return
        }
        sidebarStore.moveTabToSidebar(browserTab.data, isRight, sidebars.length)
      }
    }
  }
})

function add() {
  if (props.direction === 'top') {
    _pre_.browser.addTab()
  } else {
    layoutStore.showAddPageDialogFor(props.direction)
  }
}
</script>

<template>
  <div ref="tabElementRef" class="position-relative display-inline-block text-center">
    <!-- 拖拽指示器 -->
    <DropIndicator
      v-if="dropState.type === 'drag-over'"
      :edge="direction === 'top' ? 'left' : 'top'"
      offset="-1px"
    />
    <v-btn
      class="app-no-drag"
      color="text-on-primary"
      :data-testid="`tab-new-btn-${direction}`"
      :icon="mdiPlus"
      size="small"
      variant="plain"
      @click="add"
    />
  </div>
</template>

<style scoped></style>
